<?php
header('Content-Type: text/html; charset=utf-8');
error_reporting(E_ALL);
set_time_limit(0);
include_once dirname(dirname(dirname(dirname(dirname(__FILE__)))))."/common.php";
\ns_core\m_load::load("ns_core.m_config");
\ns_core\m_load::load("ns_core.m_file");
\ns_core\m_load::load_old("nn_logic/sync_category/sync_category.class.php");
class cms_category_sync
{
    public $str_category_sync = '';
    
    public $int_hierarchy = 32;
    
    public $str_org_id = '7173fca93fbd535824299963a6f88e39';
    
    public $obj_cms_dc = null;
    
    public $arr_sync_category = null;
    
    public $obj_dom = null;
    
//     public $arr_rule = array(
//             '1256718' => array(
//                 'level'=>3,
//                 'limit'=>4,
//             ),
//             '1256850' => array(
//                 'level'=>3,
//                 'limit'=>4,
//             ),
//             '1257008' => array(
//                 'level'=>3,
//                 'limit'=>10,
//             ),
//             '185759' => array(
//                 'level'=>3,
//                 'limit'=>1,
//             ),
//             '4372' => array(
//                 'level'=>3,
//                 'limit'=>1,
//             ),
//     );
    
    public $arr_rule = null;
    
    public $arr_md5 = null;
    
    public function __construct()
    {
        $this->obj_cms_dc = nl_get_cms_dc(array(
            'db_policy' => NL_DB_WRITE,
            'cache_policy' => NP_KV_CACHE_TYPE_MEMCACHE
        ));
        $this->obj_dom = new DOMDocument("1.0", 'utf-8');
        $this->str_category_sync = dirname(dirname(dirname(dirname(dirname(dirname(__FILE__)))))).'/data/temp/category_sync/';
    }
    
    public function init()
    {
        $this->update_cate_data(1,'0');
        if($this->check_is_exsist())
        {
            return m_config::return_data(1,'还有为扫描玩的数据站不执行下一步');
        }
        
     
        $str_xml = $this->make_asseit_xml();
//         die;
//         ob_clean();
//         header('Content-Type: text/xml; charset=utf-8');
//         echo $str_xml;die;
        $sql_asseit = "select * from nns_assists where nns_id='vod' and nns_org_type='0' and nns_org_id='{$this->str_org_id}' order by nns_create_time asc";
        $result_asseit = nl_query_by_db($sql_asseit, $this->obj_cms_dc->db());
        if(!$result_asseit)
        {
            return m_config::return_data(1,'数据库执行失败'.$sql_asseit);
        }
        $result_asseit = (isset($result_asseit[0]) && !empty($result_asseit[0]) && is_array($result_asseit[0])) ? $result_asseit[0] : null;
        $date = date("Y-m-d H:i:s");
        if(empty($result_asseit) || !is_array($result_asseit))
        {
            $array_insert = array(
                'nns_id'=>'vod',
                'nns_name'=>'播控中心vod',
                'nns_org_id'=>$this->str_org_id,
                'nns_category'=>$str_xml,
                'nns_org_type'=>'0',
                'nns_category_root_id'=>'1000',
                'nns_create_time'=>$date,
                'nns_modify_time'=>$date,
            );
            $sql_insert = nl_public::make_insert_sql('nns_assists',$array_insert);
            $result = nl_execute_by_db($sql_insert, $this->obj_cms_dc->db());
            if(!$result)
            {
                return self::return_data(1,'数据库执行失败'.$sql_insert);
            }
            return m_config::return_data(0,'ok'.$sql_insert);
        }
        if(md5($result_asseit['nns_category']) == md5($str_xml))
        {
            return m_config::return_data(0,'不需要修改');
        }
        $sql_update = "update nns_assists set nns_category='{$str_xml}',nns_modify_time='{$date}' where nns_id='vod' and nns_org_type='0' and nns_org_id='{$this->str_org_id}'  order by nns_create_time asc limit 1";
        $result = nl_execute_by_db($sql_update, $this->obj_cms_dc->db());
        if(!$result)
        {
            return self::return_data(1,'数据库执行失败'.$sql_update);
        }
        return m_config::return_data(0,'ok'.$sql_update);
    }
       
    public function check_is_exsist()
    {
        $result_file = m_file::get_files_v2($this->str_category_sync);
        if(!is_array($result_file) || empty($result_file))
        {
            return false;
        }
        foreach ($result_file as $value)
        {
            $arr_pathinfo = pathinfo($value['path']);
            $filename = (isset($arr_pathinfo['filename']) && strlen($arr_pathinfo['filename'])>0) ? trim($arr_pathinfo['filename']) : '';
            if(strlen($filename)>0 && strpos($filename, '_') !== FALSE)
            {
                return true;
            }
        }
        return false;
    }
    
    public function make_update_data($value,$key)
    {
        $key++;
        if($key >999)
        {
            return false;
        }
        if($value['nns_hierarchy'] == 1)
        {
            $value['nns_third_category_id'] = "/{$value['nns_category_id']}/";
            $value['nns_cms_category_id'] = "1000";
            $value['nns_cms_category_name'] = "/";
            return $value;
        }
        $key = (string)$key;
        if(!isset($this->arr_sync_category[(string)($value['nns_hierarchy']-1)][$value['nns_parent_id']]['nns_cms_category_id']))
        {
            return true;
        }
        if(!isset($this->arr_sync_category[(string)($value['nns_hierarchy']-1)][$value['nns_parent_id']]['nns_cms_category_name']))
        {
            return true;
        }
        if(!isset($this->arr_sync_category[(string)($value['nns_hierarchy']-1)][$value['nns_parent_id']]['nns_third_category_id']))
        {
            return true;
        }
        $value['nns_cms_category_id']=$this->arr_sync_category[(string)($value['nns_hierarchy']-1)][$value['nns_parent_id']]['nns_cms_category_id'].str_pad($key, 3, "0", STR_PAD_LEFT);
        $value['nns_cms_category_name']=$this->arr_sync_category[(string)($value['nns_hierarchy']-1)][$value['nns_parent_id']]['nns_cms_category_name'].$value['nns_name'].'/';
        $value['nns_third_category_id']=$this->arr_sync_category[(string)($value['nns_hierarchy']-1)][$value['nns_parent_id']]['nns_third_category_id'].$value['nns_category_id'].'/';
        return $value;
    }
    
    public function update_cate_data($nns_hierarchy,$parent_id='0')
    {
        $sql="select * from nns_sync_category where nns_hierarchy='{$nns_hierarchy}' and nns_parent_id='{$parent_id}' order by nns_category_id asc ";
        $result = nl_sync_category::query_sql(m_config::get_dc(),$sql);
        if($result['ret'] !=0)
        {
            return $result;
        }
        if(!isset($result['data_info']) || !is_array($result['data_info']) || empty($result['data_info']))
        {
            return m_config::return_data(0,'OK');
        }
        $result = $result['data_info'];
        foreach ($result as $key=>$value)
        {
            $temp_value = $value;
            if(strlen($value['nns_cms_category_name']) <1)
            {
                $value = $this->make_update_data($value,$key);
                if(is_bool($value))
                {
                    $this->arr_sync_category[(string)$nns_hierarchy][$value['nns_category_id']] = $temp_value;
                    continue;
                }
                $sql_update = "update nns_sync_category set nns_cms_category_name='{$value['nns_cms_category_name']}',nns_cms_category_id='{$value['nns_cms_category_id']}',nns_third_category_id='{$value['nns_third_category_id']}' where nns_id='{$value['nns_id']}'";
                $result_update = nl_sync_category::edit_sql(m_config::get_dc(),$sql_update);
                if($result_update['ret'] !=0)
                {
                    return $result_update;
                }
                $temp_value = $value;
            }
            $this->arr_sync_category[(string)$nns_hierarchy][$temp_value['nns_category_id']] = $temp_value;
            $this->update_cate_data($nns_hierarchy+1,$temp_value['nns_category_id']);
        }
        return m_config::return_data(0,'OK');
    }
     
    public function make_asseit_xml()
    {
        $assist = m_config::make_xml($this->obj_dom, 'assist');
        $this->make_xml(2,'1000',$assist);
        return $this->obj_dom->saveXML();
    }
    
    public function make_xml($nns_hierarchy,$parent_id='1000',$parent_dom)
    {
        if(is_array($this->arr_rule) && !empty($this->arr_rule))
        {
            foreach ($this->arr_rule as $key=>$value)
            {
                if($nns_hierarchy >($value['level']+$value['limit']))
                {
                    continue;
                }
                if($nns_hierarchy < $value['level'])
                {
                    $sql="select * from nns_sync_category where nns_hierarchy='{$nns_hierarchy}' and nns_cms_category_id like '{$parent_id}%' and nns_is_last !='1' order by nns_cms_category_id asc";
                }
                else
                {
                    $sql="select * from nns_sync_category where nns_hierarchy='{$nns_hierarchy}' and nns_cms_category_id like '{$parent_id}%' and nns_third_category_id like '%/{$key}/%' and nns_is_last !='1' order by nns_cms_category_id asc";
                }
                $str_md5 = md5($sql);
                if(is_array($this->arr_md5) && in_array($str_md5, $this->arr_md5))
                {
                    continue;
                }
                $this->arr_md5[] = $str_md5;
                $result = nl_sync_category::query_sql(m_config::get_dc(), $sql);
                if($result['ret'] !=0)
                {
                    return $result;
                }
                $result = isset($result['data_info']) ? $result['data_info'] : null;
                if(!is_array($result) ||empty($result))
                {
                    continue;
                }
                foreach ($result as $key=>$value)
                {
                    if($parent_id!='1000')
                    {
                        $temp_parent_id = substr($value['nns_cms_category_id'],0, -3);
                    }
                    else
                    {
                        $temp_parent_id='0';
                    }
                    $arr_attr = array(
                        'id'=>$value['nns_cms_category_id'],
                        'name'=>$value['nns_name'],
                        'subname'=>$value['nns_category_id'],
                        'parent'=>$temp_parent_id,
                        'virtual'=>"0",
                        'is_enable_area_channel_feature'=>"0",
                        'jingxuan_category_max_num'=>"",
                        'type'=>"",
                        'display'=>"0",
                        'en_US'=>"",
                        'zh_TW'=>"",
                        'zh_HK'=>""
                    );
                    $ch_dom = m_config::make_xml($this->obj_dom, 'category',null,$arr_attr,$parent_dom);
                    $this->make_xml($nns_hierarchy+1,$value['nns_cms_category_id'],$ch_dom);
                }
            }
            return m_config::return_data(0,'ok');
        }
        $sql="select * from nns_sync_category where nns_hierarchy='{$nns_hierarchy}' and nns_cms_category_id like '{$parent_id}%' and nns_is_last !='1' order by nns_cms_category_id asc";
        $result = nl_sync_category::query_sql(m_config::get_dc(), $sql);
        if($result['ret'] !=0)
        {
            return $result;
        }
        $result = isset($result['data_info']) ? $result['data_info'] : null;
        if(!is_array($result) ||empty($result))
        {
            return m_config::return_data(1,'no data');
        }
        foreach ($result as $key=>$value)
        {
            if($parent_id!='1000')
            {
                $temp_parent_id = substr($value['nns_cms_category_id'],0, -3);
            }
            else
            {
                $temp_parent_id='0';
            }
            $arr_attr = array(
                'id'=>$value['nns_cms_category_id'],
                'name'=>$value['nns_name'],
                'subname'=>$value['nns_category_id'],
                'parent'=>$temp_parent_id,
                'virtual'=>"0",
                'is_enable_area_channel_feature'=>"0",
                'jingxuan_category_max_num'=>"",
                'type'=>"",
                'display'=>"0",
                'en_US'=>"",
                'zh_TW'=>"",
                'zh_HK'=>""
            );
            $ch_dom = m_config::make_xml($this->obj_dom, 'category',null,$arr_attr,$parent_dom);
            $this->make_xml($nns_hierarchy+1,$value['nns_cms_category_id'],$ch_dom);
        }
        return m_config::return_data(0,'ok');
    }
}
$obj_cms_category_sync = new cms_category_sync();
$result = $obj_cms_category_sync->init();
echo json_encode($result);
